const tokenUtil = require("../utils/token");

module.exports = () => {
  return async function auth(ctx, next) {
    const token = ctx.headers.authorization?.split(" ")[1];
    if (!token) {
      ctx.status = 401;
      ctx.body = { code: 401, msg: "未提供token" };
      return;
    }

    try {
      const decoded = tokenUtil.verifyToken(token);
      ctx.state.user = decoded;
      await next();
    } catch (err) {
      ctx.status = 401;
      ctx.body = { code: 401, msg: "无效的token" };
    }
  };
};
